﻿using CommonLib.NetOperation;
using CommonLib.SerializeOperation;
using Models.Base;
using Models.EnumData;
using Models.Error;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFLib.ExceptionExtension;

namespace Commands.Base
{
    public class CommandHelper
    {
        /// <summary>
        /// 没有返回值的微信请求
        /// </summary>
        /// <param name="commandRequest"></param>
        public static void NoReturnWeChatRequest(BaseCommandRequest commandRequest)
        {
            string json = HttpHelper.SendHttpRequest(commandRequest.URL, commandRequest.Method, commandRequest.PostObject);

            var errorInfo = JsonParser.DeserializeFromJson<ErrorInfo>(json);

            ErrorCode errorCode = ErrorCode.Unknow;

            if (Enum.TryParse(errorInfo.ErrorCode.ToString(), out errorCode) && errorCode == ErrorCode.Success)
            {
                return;
            }
            else
            {
                throw new GException(string.Format("微信异常 - errcode:{0},errmsg:{1}", errorInfo.ErrorCode, errorInfo.ErrorMessage), WCFLib.ExceptionExtension.Enums.ExceptionType.Interrupted);
            }
        }

        /// <summary>
        /// 获取微信响应对象
        /// </summary>
        /// <typeparam name="T">响应对象类型</typeparam>
        /// <param name="commandRequest">命令请求基类</param>
        /// <returns></returns>
        public static T GetWeChatResponseObject<T>(BaseCommandRequest commandRequest)
            where T : class
        {
            string json = HttpHelper.SendHttpRequest(commandRequest.URL, commandRequest.Method);

            CheckWeChatResponseError(json);

            return JsonParser.DeserializeFromJson<T>(json);
        }

        /// <summary>
        /// 检查微信响应错误
        /// </summary>
        /// <param name="json"></param>
        /// <exception cref="WCFLib.ExceptionExtension.GException">当微信响应为异常时，将抛出ErrorCode类型的GException</exception>
        private static void CheckWeChatResponseError(string json)
        {
            if (json.StartsWith(@"{""errcode"":)"))
            {
                var errorInfo = JsonParser.DeserializeFromJson<ErrorInfo>(json);
                ErrorCode errorCode = ErrorCode.Unknow;

                if (Enum.TryParse<ErrorCode>(errorInfo.ErrorCode.ToString(), out errorCode))
                {
                    throw new GException(errorCode);
                }
                else
                {
                    throw new GException(string.Format("未知的ErrorCode - errcode:{0},errmsg:{1}", errorInfo.ErrorCode, errorInfo.ErrorMessage), WCFLib.ExceptionExtension.Enums.ExceptionType.Interrupted);
                }
            }
        }
    }
}
